package com.gj.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gj.reggie.dto.DishDto;
import com.gj.reggie.entity.Category;
import com.gj.reggie.entity.Dish;
import com.gj.reggie.entity.DishFlavor;
import com.gj.reggie.entity.R;
import com.gj.reggie.service.CategoryService;
import com.gj.reggie.service.DishFlavorService;
import com.gj.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author 郭嘉
 * @date 2022/12/30 - 15:59
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){

        dishService.saveWithFlavor(dishDto);
        //精确清理
        String key="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }

    /**
     * 才品分页
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping ("/page")
    public  R<Page> page(int page,int pageSize,String name){
        //构造分页构造对象
        Page<Dish> pageInfo=new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage=new Page<>();
        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        dishService.page(pageInfo,queryWrapper);
        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

        List<Dish> records=pageInfo.getRecords();
        List<DishDto> dishDtoList=records.stream().map((item)->{
            DishDto dishDto=new DishDto();
            //对象拷贝
            BeanUtils.copyProperties(item,dishDto);

            Long categoryId=item.getCategoryId();
            //查询分类对象
            Category category =categoryService.getById(categoryId);
            if(category!=null){
                String categoryName=category.getName();
                dishDto.setCategoryName(categoryName);
            }

            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(dishDtoList);

        return R.success(dishDtoPage);
    }

    /**
     *根据id查询菜品信息
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getDishInfo(@PathVariable Long id){
        DishDto dishDto=dishService.getDishWithFlavorById(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){

        dishService.updateWithFlavor(dishDto);

        //清理所有的菜品缓存数据
        //Set keys = redisTemplate.keys("dish_*");

        //精确清理
        String key="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("修改菜品成功");
    }


    /**
     * 停售或者起售菜品状态
     * @param ids
     * @param status
     * @return
     */
    @PostMapping("/status/{params.status}")
    public R<String> updateDish(@PathVariable("params.status") Integer status,Long[] ids){
        //log.info("status ={},id={}",status,ids);
        dishService.updateDishStatus(ids,status);
        return R.success("更新状态成功");
    }

    /**
     * 删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> deleteDish(Long[] ids){
        //log.info("ids={}",ids);
        dishService.deleteDishWithFlavor(ids);
        return R.success("删除菜品成功");
    }

    /**
     * 根据条件查菜品数据
     * @param dish
     * @return
    @GetMapping("/list")
    public R<List<Dish>> selectDishList(Dish dish){

        //构建查询对象
        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //起售状态为1才能查到
        queryWrapper.eq(Dish::getStatus,1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list=dishService.list(queryWrapper);
        return R.success(list);
    }*/

    /**
     * 根据条件查菜品数据
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> selectDishList(DishDto dish){
        List<DishDto> dtoList=null;

        String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        //先从redis中获取缓存数据
        dtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        //若存在，无需查询数据库
        if(dtoList!=null){
            return R.success(dtoList);
        }



        //构建查询对象
        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //起售状态为1才能查到
        queryWrapper.eq(Dish::getStatus,1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list=dishService.list(queryWrapper);

         dtoList=list.stream().map((item)->{
            DishDto dishDto=new DishDto();
            //对象拷贝
            BeanUtils.copyProperties(item,dishDto);

            Long categoryId=item.getCategoryId();
            //查询分类对象
            Category category =categoryService.getById(categoryId);
            if(category!=null){
                String categoryName=category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //当前菜品id
            Long dishId=item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavorList=dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());
         //不存在，则查询数据库添加到redis中
         redisTemplate.opsForValue().set(key,dtoList,60, TimeUnit.MINUTES);

        return R.success(dtoList);
    }

}
